package com.jyniubi.gmall.payment.Controller;

import com.alibaba.fastjson.JSON;
import com.alipay.api.AlipayApiException;
import com.jyniubi.gmail.common.bean.ResponseVo;
import com.jyniubi.gmail.common.exception.OrderException;
import com.jyniubi.gmall.oms.entity.OrderEntity;
import com.jyniubi.gmall.payment.config.AlipayTemplate;
import com.jyniubi.gmall.payment.feign.GmallOmsClient;
import com.jyniubi.gmall.payment.interceptor.LoginInterceptor;
import com.jyniubi.gmall.payment.pojo.UserInfo;
import com.jyniubi.gmall.payment.service.PaymentService;
import com.jyniubi.gmall.payment.vo.PayAsyncVo;
import com.jyniubi.gmall.payment.vo.PayVo;
import com.jyniubi.gmall.payment.vo.PaymentInfoEntity;
import org.apache.commons.lang.StringUtils;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import java.math.BigDecimal;
import java.util.Date;

@Controller
public class PaymentController {
    @Autowired
    private PaymentService paymentService;
    @Autowired
    private GmallOmsClient omsClient;

    @Autowired
    private AlipayTemplate alipayTemplate;

    @Autowired
    private RabbitTemplate rabbitTemplate;

    @GetMapping("alipay.html")
    @ResponseBody
    public String aligay(@RequestParam("orderToken")String orderToken){
        ResponseVo<OrderEntity> orderEntityResponseVo = this.omsClient.queryOrderByToken(orderToken);
        OrderEntity orderEntity = orderEntityResponseVo.getData();
        if (orderEntity == null){
            throw new OrderException("此订单不存在!");
        }
        if (orderEntity.getStatus() != 0){
            throw new OrderException("此订单不可支付！");
        }
        UserInfo userInfo = LoginInterceptor.getUserInfo();
        Long userId = userInfo.getUserId();
        if (!orderEntity.getUserId().equals(userId)){
            throw new OrderException("此订单不属于你！");
        }

        try {
            PayVo payVo = new PayVo();
            payVo.setOut_trade_no(orderEntity.getOrderSn());
            payVo.setTotal_amount("0.01");
            payVo.setSubject("支付平台");
            Long payId = this.paymentService.savePayInfo(orderEntity,1);
            payVo.setPassback_params(payId.toString());
            return this.alipayTemplate.pay(payVo);
        } catch (AlipayApiException e) {
            e.printStackTrace();
            throw new OrderException("跳转支付页面失败，请重试！");
        }
    }

    /**
     * 跳转到选择支付方式页面
     * @param orderToken
     * @param model
     * @return
     */
    @GetMapping("pay.html")
    public String paySelect(@RequestParam("orderToken")String orderToken, Model model){
        ResponseVo<OrderEntity> orderEntityResponseVo = this.omsClient.queryOrderByToken(orderToken);
        OrderEntity orderEntity = orderEntityResponseVo.getData();
        if (orderEntity == null){
            throw new OrderException("此订单不存在!");
        }
        if (orderEntity.getStatus() != 0){
            throw new OrderException("此订单不可支付！");
        }
        UserInfo userInfo = LoginInterceptor.getUserInfo();
        Long userId = userInfo.getUserId();
        if (!orderEntity.getUserId().equals(userId)){
            throw new OrderException("此订单不属于你！");
        }
        model.addAttribute("orderEntity",orderEntity);
        return "pay";
    }

    /**
     * 同步回调只做页面展示
     * @return
     */
    @GetMapping("pay/success")
    public String paySuccess(){
        return "paySuccess";
    }


    /**
     * 异步回调是否支付成功
     * @return
     */
    @PostMapping("pay/ok")
    @ResponseBody
    public String payOk(PayAsyncVo payAsyncVo){
        // 1.验签：确保该回调是由支付宝发送的
        Boolean flag = this.alipayTemplate.checkSignature(payAsyncVo);
        if (!flag){
            return "failure";
        }
        // 2.校验业务参数：app_id out_trade_no total_amount
        if (payAsyncVo == null){
            return "failure";
        }
        String app_id = payAsyncVo.getApp_id();
        String out_trade_no = payAsyncVo.getOut_trade_no();
        String total_amount = payAsyncVo.getTotal_amount();
        String payId = payAsyncVo.getPassback_params();
        PaymentInfoEntity paymentInfoEntity = this.paymentService.queryPaymentInfoById(payId);
        if (paymentInfoEntity == null || StringUtils.equals(app_id,this.alipayTemplate.getApp_id()) ||
         StringUtils.equals(out_trade_no,paymentInfoEntity.getOutTradeNo()) ||
         new BigDecimal(total_amount).compareTo(paymentInfoEntity.getTotalAmount()) != 0){
            return "failure";
        }
        // 3.判断支付状态
        if (!"TRADE_SUCCESS".equals(payAsyncVo.getTrade_status())){
            return "failure";
        }
        // 4. 更改对账记录，修改为已支付
        paymentInfoEntity.setPaymentStatus(1);
        paymentInfoEntity.setTradeNo(payAsyncVo.getTrade_no());
        paymentInfoEntity.setCallbackTime(new Date());
        paymentInfoEntity.setCallbackContent(JSON.toJSONString(payAsyncVo));
        if (this.paymentService.updatePaymentInfo(paymentInfoEntity) == 1){
            // 5.发送消息给OMS更新订单状态（oms->wms发送消息减库存）
            this.rabbitTemplate.convertAndSend("ORDER.EXCHANGE","order.pay",out_trade_no);
        }

        return "success";
    }
}
